<?php

use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Configuration,
    Doctrine\ORM\EntityManager,
    Doctrine\Common\Cache\ArrayCache,
	Doctrine\ORM\Mapping\Driver\YamlDriver,
	Cekurte\Logging\Sql;

class Bootstrap extends \Zend_Application_Bootstrap_Bootstrap
{	
	/**
	 * Define as constantes utilizadas na aplicação
	 * 
	 * @author 	João Paulo Cercal
	 * @version 1.0
	 */
	public function _initConstants()
	{
		$constants 	= $this->getOption('constants');
		
		$request 	= new \Zend_Controller_Request_Http();
		
		defined( 'BASE_URL' )
    			|| define( 'BASE_URL' , $request->getBaseUrl() );
		
		foreach( $constants as $constant => $value )
		{
			$constant = strtoupper($constant);
			
			defined( $constant )
    			|| define( $constant , BASE_URL . '/' . $value );
		}
	}
	
	/**
	 * Configura as rotas utilizadas na aplicação
	 * 
	 * @author 	João Paulo Cercal
	 * @version 1.0
	 */
	public function _initRouter()
	{
		$router 	= \Zend_Controller_Front::getInstance()->getRouter();
		
		$config 	= new \Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini');
		
		$router->addConfig( $config, 'routes' );	
	}

	/**
	* Configura o ORM Doctrine 2
	*
	* @author João Paulo Cercal
	* @version 1.0
	*/
	public function _initDoctrine () 
	{
		// Configura o carregamento das classes...
		require_once 'Doctrine/Common/ClassLoader.php';

		$doctrineClassLoader = new ClassLoader('Doctrine\Common', 	LIBRARY_PATH );
		$doctrineClassLoader->register();

		$doctrineClassLoader = new ClassLoader('Doctrine\DBAL', 	LIBRARY_PATH );
		$doctrineClassLoader->register();

		$doctrineClassLoader = new ClassLoader('Doctrine\ORM', 		LIBRARY_PATH );
		$doctrineClassLoader->register();

		$doctrineClassLoader = new ClassLoader('Symfony', 			LIBRARY_PATH . '/Doctrine' );
		$doctrineClassLoader->register();
	
		$entitiesClassLoader = new ClassLoader('Entities', 			APPLICATION_PATH );
		$entitiesClassLoader->register();
		
		$proxiesClassLoader = new ClassLoader('Proxies', 			APPLICATION_PATH );
		$proxiesClassLoader->register();
		
		// Pega os parametros de configuração do doctrine do arquivo "ini"
		$doctrine_ini = $this->getOption('doctrine');
	 
		// Configura o cache
		$config = new Configuration();
		$cache 	= new ArrayCache();
		
		$config->setMetadataCacheImpl($cache);
		$config->setQueryCacheImpl($cache);
	 
		// Configura o driver, utilizando YAML como padrão
		$driver = new YamlDriver( $doctrine_ini['config']['yaml']['dir'] );
		$config->setMetadataDriverImpl($driver);
	 
		// Configuração de Proxy
		$config->setProxyDir( $doctrine_ini['config']['proxy']['dir'] );
		$config->setProxyNamespace( $doctrine_ini['config']['proxy']['namespace'] );
	 
		// Configura o Logger
		if( $doctrine_ini['config']['sql']['logger']  === '1' )
		{
			$logger = new Sql();
			$config->setSqlLogger($logger);
		}
		
		// Configura a auto-geração de classes proxy
		// Se o ambiente for desenvolvimento true, do contrário false
		$config->setAutoGenerateProxyClasses( (APPLICATION_ENV === 'development') );

		// Configura as informações de conexão com o banco de dados
		$connectionOptions = array(
			'driver'    => $doctrine_ini['connection']['driver'],
            'user'      => $doctrine_ini['connection']['username'],
            'password'  => $doctrine_ini['connection']['password'],
            'dbname'    => $doctrine_ini['connection']['database'],
            'host'      => $doctrine_ini['connection']['hostname']
		);
		
		// Cria o gerenciador de entidades
		$entityManager = EntityManager::create($connectionOptions, $config );
		
        // Obtém o Registro da aplicação
        $registry = Zend_Registry::getInstance();
        
		// Adiciona ao registro o gerenciador de entidades
        $registry->entityManager = $entityManager;
 
        return $entityManager;
	}
	
}

